package com.process.shareMemory;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class SharedMemoryConsumer {
    public static void main(String[] args) throws InterruptedException {
        try {
            // 创建文件和文件通道
            RandomAccessFile file = new RandomAccessFile("D:\\shared_memory.dat", "rw");
            FileChannel channel = file.getChannel();

            // 创建共享内存缓冲区
            MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);

            // 消费者进程从共享内存读取数据
            while (true) {
                if (!buffer.hasRemaining()) {
                    System.out.print("睡了\n");
                    Thread.sleep(1000);
                }
                else {
                    byte[] data = new byte[buffer.remaining()];
                    buffer.get(data);
                    String strData = new String(data);
                    System.out.println("Consumer: " + strData);
                }

            }

            // 关闭文件通道和文件

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
